package com.youdianstar.app.ui

import android.os.Bundle
import android.view.View
import com.youdianstar.app.R
import com.youdianstar.app.BR
import com.youdianstar.app.common.Extra
import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.common.network.BaseApiResultObserver
import com.youdianstar.app.common.util.StrUtil
import com.youdianstar.app.databinding.ActivityScanResultBinding
import com.youdianstar.app.entity.RentboxConfig
import com.youdianstar.app.util.DataHelperEx
import com.google.gson.Gson
import com.gyf.immersionbar.ImmersionBar
import org.koin.androidx.viewmodel.ext.android.viewModel

class ScanResultActivity : BaseActivity<ActivityScanResultBinding, ScanViewModel>() {

    override fun layoutId(): Int = R.layout.activity_scan_result

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): ScanViewModel {
        val model: ScanViewModel by viewModel()
        return model
    }

    private var deviceId: String = ""
    private var powerBankType: Int = 0
    private var securityFee: Double = 250000.0

    override fun initData() {
        super.initData()
        
        // 初始化HeadBar
        mBinding.headBar.initTitle(this, getString(R.string.scan_result_title), showInner = false)
        
        // 获取传递的deviceId
        deviceId = intent.getStringExtra(Extra.IT_MSG) ?: ""
        
        if (StrUtil.isEmpty(deviceId)) {
            showError(getString(R.string.scan_result_deviceIdEmpty))
            return
        }

        // 初始化显示机柜SN标签
        mBinding.tvDeviceLabel.text = getString(R.string.scan_result_stationSN, deviceId)
        
        // 隐藏结果和按钮，显示加载
        mBinding.progressLayout.visibility = View.VISIBLE
        mBinding.resultScrollView.visibility = View.GONE
        mBinding.btnConfirm.visibility = View.GONE
        mBinding.errorLayout.visibility = View.GONE

        // 调用接口查询机柜信息
        mViewModel.getScanResult(deviceId)
    }

    override fun initClickEvent() {
        mBinding.btnRescan.setOnClickListener {
            finish()
        }
        
        mBinding.btnConfirm.setOnClickListener {
            // 跳转到押金支付页面
            val intent = android.content.Intent(this@ScanResultActivity, DepositPaymentActivity::class.java)
            intent.putExtra(Extra.IT_MSG, deviceId)
            intent.putExtra("powerBankType", powerBankType)
            intent.putExtra("securityFee", securityFee)
            startActivity(intent)
        }
    }

    override fun initLiveObserver() {
        super.initLiveObserver()
        
        // 监听扫码结果
        mViewModel.scanResultLiveData.observe(this, object : BaseApiResultObserver<Any>(true) {
            override fun onDataResult(data: Any?) {
                android.util.Log.d("ScanResultActivity", "========= 收到扫码结果 =========")
                android.util.Log.d("ScanResultActivity", "data类型: ${data?.javaClass}")
                android.util.Log.d("ScanResultActivity", "data内容: ${data}")
                super.onDataResult(data)
                dismissDialog()
                
                // 显示结果
                mBinding.progressLayout.visibility = View.GONE
                mBinding.errorLayout.visibility = View.GONE
                mBinding.resultScrollView.visibility = View.VISIBLE
                mBinding.btnConfirm.visibility = View.VISIBLE
                
                android.util.Log.d("ScanResultActivity", "显示结果页面")
                
                // 更新机柜SN标签
                mBinding.tvDeviceLabel.text = getString(R.string.scan_result_stationSN, deviceId)
                
                // 解析返回的数据并设置计费规则
                try {
                    android.util.Log.d("ScanResultActivity", "开始解析数据，data类型: ${data?.javaClass}")
                    
                    // data直接就是Map类型
                    val dataMap = data as? Map<*, *>
                    if (dataMap != null) {
                        android.util.Log.d("ScanResultActivity", "data是Map类型，keys: ${dataMap.keys}")
                        
                        // 获取config字段
                        val configMap = dataMap["config"] as? Map<*, *>
                        if (configMap != null) {
                            android.util.Log.d("ScanResultActivity", "找到config，keys: ${configMap.keys}")
                            
                            val gson = Gson()
                            val configJson = gson.toJson(configMap)
                            val config = gson.fromJson(configJson, RentboxConfig::class.java)
                            
                            android.util.Log.d("ScanResultActivity", "解析config成功: minuteFree=${config.minuteFree}, cycleFee=${config.cycleFee}")
                            
                            // 保存押金金额
                            securityFee = config.securityFee
                            
                            // 使用DataHelperEx格式化计费规则
                            val billingText = DataHelperEx.rentboxConfigPlanTx(this@ScanResultActivity, config)
                            android.util.Log.d("ScanResultActivity", "格式化后的计费规则: $billingText")
                            mBinding.tvBillingRules.text = billingText
                        } else {
                            android.util.Log.e("ScanResultActivity", "未找到config字段")
                            mBinding.tvBillingRules.text = getString(R.string.scan_result_noBillingRules)
                        }
                        
                        // 获取rentbox信息
                        val rentboxMap = dataMap["rentbox"] as? Map<*, *>
                        if (rentboxMap != null) {
                            powerBankType = (rentboxMap["powerbankType"] as? Number)?.toInt() ?: 0
                        }
                    } else {
                        android.util.Log.e("ScanResultActivity", "data不是Map类型")
                        mBinding.tvBillingRules.text = getString(R.string.scan_result_noBillingRules)
                    }
                } catch (e: Exception) {
                    android.util.Log.e("ScanResultActivity", "解析计费规则失败", e)
                    e.printStackTrace()
                    mBinding.tvBillingRules.text = getString(R.string.scan_result_noBillingRules)
                }
            }

            override fun onNetError(code: Int, e: String?) {
                android.util.Log.e("ScanResultActivity", "========= 扫码结果接口错误 =========")
                android.util.Log.e("ScanResultActivity", "HTTP code=$code, error message=$e")
                super.onNetError(code, e)
                dismissDialog()
                // 显示统一的错误信息
                showError(getString(R.string.scan_result_deviceNotFound))
            }
        })
    }

    private fun showError(message: String) {
        mBinding.progressLayout.visibility = View.GONE
        mBinding.errorLayout.visibility = View.VISIBLE
        mBinding.resultScrollView.visibility = View.GONE
        mBinding.btnConfirm.visibility = View.GONE
        mBinding.btnRescan.visibility = View.VISIBLE
        mBinding.tvErrorMessage.text = message
    }
}

